package com.jason.demo.servicehi.concurrent.con1;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zhouxinghuai
 * @description description
 * @date 2018-09-10
 */
public class ConditionWaitDemo implements Runnable {

    private Lock lock;
    private Condition condition;

    public ConditionWaitDemo(Lock lock, Condition condition) {
        this.lock = lock;
        this.condition = condition;
        System.out.println(this.getClass() + "\t" + Thread.currentThread().getName());
    }

    @Override
    public void run() {
        System.out.println("begin -ConditionDemoWait");
        try {
            lock.lock();
            condition.await();
            System.out.println("end - ConditionDemoWait");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }


    public static void main(String[] args) throws InterruptedException {
        Lock lock = new ReentrantLock();
        Condition condition = lock.newCondition();

        ConditionWaitDemo conditionWaitDemo = new ConditionWaitDemo(lock, condition);
        ConditionSignalDemo conditionSignalDemo = new ConditionSignalDemo(lock, condition);
        Thread threadWait = new Thread(conditionWaitDemo);


        Thread threadSignal = new Thread(conditionSignalDemo);

        threadWait.start();
        Thread.sleep(2000);
        threadSignal.start();
    }

}
